package com.browsesoft.baseadapter;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.browsesoft.tools.BSCalendar;

public class OndutyModel extends HTMLBasicTableModelAdapter {

	private BSCalendar now = BSCalendar.now();

	public void init(HttpServletRequest request) throws Exception {
		super.init(request);
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.service(request, response);
		String type = this.component.getElement().getAttribute("ondutytype");
		// 根据值班类型过滤
		this.datas = dataFilter(this.datas, type);
		// 根据要求显示的时间范围过滤
		String timeArea = this.component.getElement().getAttribute("timearea");
		if (timeArea != null && !timeArea.equals("")) {
			this.datas = dataFilterWithTime(this.datas, timeArea);
		}
	}

	/**
	 * 根据要求显示的时间范围过滤 单位为天，从当前时间开始往后的多少天范围
	 */
	private List dataFilterWithTime(List datas, String timeArea) {
		List result = new LinkedList();
		Iterator iter = datas.iterator();
		while (iter.hasNext()) {
			SimpleEntity item = (SimpleEntity) iter.next();
			if (isTimeArea(item, timeArea)) {
				result.add(item);
			}
		}
		return result;
	}

	/**
	 * 判断实体是否为指定的时间范围内的数据
	 */
	private boolean isTimeArea(SimpleEntity item, String timeArea) {
		String startTime = (String) item.getAttributes().get("f_starttime");
		BSCalendar afterDay = now.getCalendarAfterDay(Integer
				.parseInt(timeArea));
		if ((startTime.substring(0, 10).compareTo(now.toString("yyyy-mm-dd")) >= 0)
				&& (startTime.substring(0, 10).compareTo(
						afterDay.toString("yyyy-mm-dd")) <= 0)) {
			return true;
		}
		return false;
	}

	/**
	 * 根据值班类型过滤
	 */
	private List dataFilter(List datas, String type) {
		LinkedList result = new LinkedList();
		Iterator iter = datas.iterator();
		while (iter.hasNext()) {
			SimpleEntity item = (SimpleEntity) iter.next();
			String onDutyType = (String) item.getAttributes().get(
					"zhibanleixing");
			if (onDutyType != null && onDutyType.equals(type)) {
				result.add(item);
			}
		}
		return result;
	}
}
